package kamikaze.service.product;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kamikaze.bean.Product;
import kamikaze.service.ErrorHandler;
import kamikaze.service.UserSession;
import kamikaze.utils.Database;
import kamikaze.utils.Database.Template;

public class RetrieveProductServlet extends HttpServlet {


	private static final long serialVersionUID = -8355357668897739770L;
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		new ErrorHandler(Arrays.asList("Method is not supported")).handle(req, resp);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
			throws ServletException, IOException {
		List<Product> productList = new ArrayList<Product>();
		
		try {
			
			productList = (List<Product>) Database.get().execute(new Template<Object>() {

				@Override
				public Object query(EntityManager em) {

					Query q = em.createQuery("Select p from Product p where deleted=false and ownerKey= :ownerKey");
					q.setParameter("ownerKey", UserSession.getFrom(req).getKey().getId());
					List<Product> products = q.getResultList();

					return products;
				}
			});

		} catch (Exception ex) {
			new ErrorHandler(Arrays.asList(ex.getMessage())).handle(req, resp);
			return;
		}

		req.setAttribute("products", productList);
		req.getRequestDispatcher("/productlist.jsp").forward(req, resp);
	}


}
